class FileUtils {
    // Base64编码
    static async encodeFile(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => {
                const base64String = reader.result.split(',')[1];
                resolve(base64String);
            };
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
    }

    // Base64解码并创建Blob URL
    static decodeToUrl(base64String, mimeType = 'image/jpeg') {
        try {
            const binaryString = window.atob(base64String);
            const bytes = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            const blob = new Blob([bytes], { type: mimeType });
            return URL.createObjectURL(blob);
        } catch (error) {
            console.error('Base64解码失败:', error);
            return null;
        }
    }

    // 清理Blob URL
    static revokeUrl(url) {
        URL.revokeObjectURL(url);
    }

    // 添加文件下载方法
    static downloadFile(base64Data, fileName, mimeType = 'application/octet-stream') {
        try {
            const binaryString = window.atob(base64Data);
            const bytes = new Uint8Array(binaryString.length);
            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            const blob = new Blob([bytes], { type: mimeType });
            const url = URL.createObjectURL(blob);
            
            const link = document.createElement('a');
            link.href = url;
            link.download = fileName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        } catch (error) {
            console.error('文件下载失败:', error);
            throw error;
        }
    }
} 